package com.example.filter;

import com.example.utils.Const;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 自定义CORS过滤器，解决前后端跨域请求问题
 *
 * @auth shanyue
 * @date 2025年06月20日15:22
 */
@Component
@Order(Const.ORDER_CORS)
public class CorsFilter extends HttpFilter {

    /**
     * 每次Http请求进入后，都调用此方法
     * 在请求传递前，先添加跨域所需的响应头
     * @param request   HTTP请求对象
     * @param response  HTTP响应对象
     * @param chain 过滤器链
     * @throws IOException  IO异常
     * @throws ServletException Servlet异常
     */
    @Override
    protected void doFilter(HttpServletRequest request,
                            HttpServletResponse response,
                            FilterChain chain) throws IOException, ServletException {
        //添加开宇响应头
        this.addCorsHeader(request,response);
        //放行请求，继续执行下一个过滤器
        chain.doFilter(request,response);
    }

    /**
     * 先响应头中添加CORS相关的头部信息，允许前端跨域访问
     * @param request   HTTP请求对象
     * @param response  HTTP响应对象
     */
    private void addCorsHeader(HttpServletRequest request,
                               HttpServletResponse response){
        //允许前端地址的跨域请求
        response.addHeader("Access-Control-Allow-Origin","http://localhost:5173");
        //允许请求方法
        response.addHeader("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");
        //允许前端携带自定义请求头
        response.addHeader("Access-Control-Allow-Headers","Authorization,Content-type");
    }

}
